package com.util.download.core;

import com.util.download.constant.Constant;
import com.util.download.util.FileUtil;
import com.util.download.util.HttpClientUtil;
import com.util.download.util.LogUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DownLoader {

    /**
     * 创建线程池
     */
    public ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    /**
     * 下载
     * @param url
     */
    public void download(String url) {
        String httpFileName = HttpClientUtil.getHttpFileName(url);

        httpFileName = Constant.FILE_PATH + httpFileName;

        long localFileLength = FileUtil.getFileContent(httpFileName);
        DownloadInfoThread downloadInfoThread = null;
        // 获取连接对象
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = HttpClientUtil.getHttpUrlConnection(url);

            int contentLength = httpURLConnection.getContentLength();

            if (localFileLength >= contentLength) {
                LogUtil.info("{}文件已下载，无需重新下载",httpFileName);
                return ;
            }

             downloadInfoThread = new DownloadInfoThread(contentLength);
            // 将任务交给线程池，每隔一秒执行一次
            scheduledExecutorService.scheduleAtFixedRate(downloadInfoThread,1,1, TimeUnit.SECONDS);

        } catch (IOException e) {
            e.printStackTrace();
        }

        try (
                // 获取网络上文件的输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                // 将数据写入到缓冲流
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

                FileOutputStream fileOutputStream = new FileOutputStream(httpFileName);
                // 将内存中的数据 输出到硬盘中去
                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
        ) {
            int len = -1;
            byte[] buffer = new byte[Constant.BUFFER_SIZE];
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                downloadInfoThread.downSize += len;
                bos.write(buffer,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LogUtil.error("下载的文件不存在---->{}", url);
        } catch (Exception e) {
            LogUtil.error("下载失败");
        } finally {
            System.out.println("/r");
            System.out.println("=========== 下载完成 ========= ");
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            // 关闭线程池
            scheduledExecutorService.shutdown();
        }

    }
}
